/*
 * @Description: 生成MapperXml
 * @Author: DHL
 * @Date: 2022-01-30 14:20:12
 * @LastEditors: DHL
 * @LastEditTime: 2023-06-20 14:28:23
 */

import { firstToUpperCase, firstToLowerCase, getJdbcType } from '../../utils/codeGenUtils'

export function createMapperXml(codeGenConfig: any) {
  const classNameFirstToUpperCase = firstToUpperCase(codeGenConfig.className)
  const classNameFirstToLowerCase = firstToLowerCase(codeGenConfig.className)
  const classNameInterface = 'I' + codeGenConfig.className + 'Service'
  const className = codeGenConfig.className + 'Service'

  return `<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<!-- 符号转义说明 -->
<!-- 【&lt;】 【<】 -->
<!-- 【&gt;】 【>】 -->
<!-- 【&lt;&gt;】 【<>】 -->
<!-- 【&amp;】 【&】 -->
<!-- 【&apos;】 【'】 -->
<!-- 【&apos;】 【'】 -->
<!-- 【&quot;】 【"】 -->
<!-- <![CDATA[ 这里写你的SQL或者符号 ]]> -->

<!-- ${codeGenConfig.genAuthor} ${codeGenConfig.createData} -->
<!-- ${codeGenConfig.genName} -->

<mapper namespace="${codeGenConfig.packageName}.mapper.${classNameFirstToUpperCase}Mapper">

  <!-- 查询条件 包含所有 -->
  <sql id="searchWhere">
    <trim prefix="WHERE" prefixOverrides="AND | OR">
      and t.isdel = 0
      ${getSearchWhere(codeGenConfig.optionsJson.columns)}
      <if test="queryLikeStr != null and queryLikeStr != ''">
      </if>
    </trim>
  </sql>


  <!-- 查询字段 -->
	<sql id="searchFields">
		<trim suffixOverrides=",">
		  ${getSearchFields(codeGenConfig.optionsJson.columns)}
		</trim>
	</sql>


  <!-- 查询、统计共用 -->
  <sql id="searchCommon">
    select <include refid="searchFields" />
    from ${codeGenConfig.tableName.toLowerCase()} t
    <include refid="searchWhere" />
  </sql>
  

  <!-- 系统配置查询 -->
	<select id="search${classNameFirstToUpperCase}" parameterType="${
    codeGenConfig.packageName
  }.entity.${classNameFirstToLowerCase}.vo.Search${classNameFirstToUpperCase}Vo" resultType="${
    codeGenConfig.packageName
  }.entity.${classNameFirstToLowerCase}.dto.Search${classNameFirstToUpperCase}Dto">
		<include refid="searchCommon"/>
	</select>

  <!-- 系统配置查询合计, 根据业务重写sql -->
	<select id="search${classNameFirstToUpperCase}Sum" parameterType="${
    codeGenConfig.packageName
  }.entity.${classNameFirstToLowerCase}.vo.Search${classNameFirstToUpperCase}Vo" resultType="${
    codeGenConfig.packageName
  }.entity.${classNameFirstToLowerCase}.dto.Search${classNameFirstToUpperCase}Dto">
		select ${getTableColumnsMoney(codeGenConfig.optionsJson.columns)}
    from ( <include refid="searchCommon"/> ) tt
	</select>

  <!-- 批量逻辑删除 -->
	<update id="logicBatchDelete${classNameFirstToUpperCase}ByIds" parameterType="java.util.List">
		update ${codeGenConfig.tableName.toLowerCase()}
			set isdel = 1 	<!-- 逻辑删除 -->
		where id in 	<!-- 序号 -->
		<foreach collection="list" item="item" index="index" open="(" separator="," close=")">
			#{item}
		</foreach>
	</update>

</mapper>
`
}

/**
 * 获取查询条件
 * @param columns
 */
function getSearchWhere(columns: any) {
  let where: Array<string> = []

  columns.forEach((item: any) => {
    if (item.query) {
      switch (item.queryWay) {
        case 'like':
          where.push(
            `
      <if test='${getSearchWhereIf(item)}'>
        and t.${item.columnName.toLowerCase()} like CONCAT('%',#{${
              item.javaField
            }, jdbcType=${getJdbcType(item.dataType)}},'%')	<!-- ${item.javaComment} -->
      </if>`
          )
          break

        case '!=':
          where.push(
            `
      <if test='${getSearchWhereIf(item)}'>
        and t.${item.columnName.toLowerCase()} <![CDATA[ <> ]]> #{${
              item.javaField
            }, jdbcType=${getJdbcType(item.dataType)}} <!-- ${item.javaComment} -->
      </if>`
          )
          break

        case '>':
          where.push(
            `
      <if test='${getSearchWhereIf(item)}'>
        and t.${item.columnName.toLowerCase()} <![CDATA[ > ]]> #{${
              item.javaField
            }, jdbcType=${getJdbcType(item.dataType)}} <!-- ${item.javaComment} -->
      </if>`
          )
          break

        case '<':
          where.push(
            `
      <if test='${getSearchWhereIf(item)}'>
        and t.${item.columnName.toLowerCase()} <![CDATA[ < ]]> #{${
              item.javaField
            }, jdbcType=${getJdbcType(item.dataType)}} <!-- ${item.javaComment} -->
      </if>`
          )
          break

        case '>=':
          where.push(
            `
      <if test='${getSearchWhereIf(item)}'>
        and t.${item.columnName.toLowerCase()} <![CDATA[ >= ]]> #{${
              item.javaField
            }, jdbcType=${getJdbcType(item.dataType)}} <!-- ${item.javaComment} -->
      </if>`
          )
          break

        case '<=':
          where.push(
            `
      <if test='${getSearchWhereIf(item)}'>
        and t.${item.columnName.toLowerCase()} <![CDATA[ <= ]]> #{${
              item.javaField
            }, jdbcType=${getJdbcType(item.dataType)}} <!-- ${item.javaComment} -->
      </if>`
          )
          break

        case 'between':
          where.push(
            `
      <if test='${getSearchWhereIf(item, 'Begin')}'>
        and t.${item.columnName.toLowerCase()} <![CDATA[ >= ]]> #{${
              item.javaField
            }Begin, jdbcType=${getJdbcType(item.dataType)}} <!-- ${item.javaComment} - 开始 -->
      </if>
  
      <if test='${getSearchWhereIf(item, 'End')}'>
        and t.${item.columnName.toLowerCase()} <![CDATA[ <= ]]> #{${
              item.javaField
            }End, jdbcType=${getJdbcType(item.dataType)}} <!-- ${item.javaComment} - 结束 -->
      </if>`
          )
          break

        default:
          where.push(
            `
      <if test='${getSearchWhereIf(item)}'>
        and t.${item.columnName.toLowerCase()} = #{${item.javaField}, jdbcType=${getJdbcType(
              item.dataType
            )}}	<!-- ${item.javaComment} -->
      </if>`
          )
          break
      }
    }
  })

  return where.join('')
}

/**
 * 获取查询条件if内容
 * @param column
 */
function getSearchWhereIf(column: any, suffix = '') {
  const javaField = `${column.javaField}${suffix}`

  if ('String' === column.javaType) {
    return `${javaField} != null and ${javaField} != ""`
  } else {
    return `${javaField} != null`
  }
}

/**
 * 查询字段
 * @param columns
 */
function getSearchFields(columns: any) {
  let field: Array<string> = []

  columns.forEach((item: any) => {
    const fieldName = item.columnName.toLowerCase()
    if (fieldName.charAt(fieldName.length - 1) === '_') {
      field.push(`t.${item.columnName.toLowerCase()} as ${fieldName.substr(
        0,
        fieldName.length - 1
      )},  <!-- ${item.javaComment} -->
      `)
    } else {
      field.push(`t.${item.columnName.toLowerCase()},  <!-- ${item.javaComment} -->
      `)
    }
  })
  return field.join('')
}

/**
 * 获取表格金额列
 * @param columns
 */
function getTableColumnsMoney(columns: any) {
  let field: Array<string> = []

  columns.forEach((item: any) => {
    if (item.componentType === 'money') {
      const columnName = item.columnName.toLowerCase()
      field.push(`
      sum(tt.${columnName}) as ${columnName}`)
    }
  })

  return field.join(',')
}
